#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<unordered_set>
using namespace std;


struct ListNode{
    int val;
    ListNode* next;
    ListNode(int x): val(x), next(nullptr){}
};

class Solution{
    public:
    pair<ListNode*, ListNode*> myReverse(ListNode* head, ListNode* tail) {
        ListNode* prev = tail->next;
        ListNode* p = head;
        while (prev != tail) {
            ListNode* nex = p->next;
            p->next = prev;
            prev = p;
            p = nex;
        }
        return {tail, head};
    }


    ListNode* ans1(ListNode* head, int k){
        ListNode* newhead = new ListNode(-1);
        newhead->next = head;
        ListNode* temp = newhead;
        while(head){
            ListNode* tail = temp;
            for(int i = 0; i != k; i++){
                tail = tail->next;
                if(!tail){
                    return newhead->next;
                }
            }
            // ListNode* nex = tail->next;
            tie(head, tail) = myReverse(head, tail);
            temp->next = head;
            // tail->next = nex;
            temp = tail;
            head = tail->next;
        }
        
        return newhead->next;
    }

};

void test1(){
    vector<int> num = {1,2,3,4,5};
    ListNode* head = nullptr;
    ListNode* tail = nullptr;
    for(int i = 0; i != num.size(); i++){
        if(!head){
            head = tail = new ListNode(num[i]);
        }else{
            tail->next = new ListNode(num[i]);
            tail = tail->next;
        }
    }
    int k = 2;

    Solution s;
    ListNode* ret = s.ans1(head, k);
    while(ret){
        cout << ret->val << " " << ends;
        ret = ret->next;
    }
    cout << endl;
}

void test2(){
    vector<int> num = {1,2,3,4,5};
    ListNode* head = nullptr;
    ListNode* tail = nullptr;
    for(int i = 0; i != num.size(); i++){
        if(!head){
            head = tail = new ListNode(num[i]);
        }else{
            tail->next = new ListNode(num[i]);
            tail = tail->next;
        }
    }
    int k = 3;

    Solution s;
    ListNode* ret = s.ans1(head, k);
    while(ret){
        cout << ret->val << " " << ends;
        ret = ret->next;
    }
    cout << endl;
}


int main(void){
    test1();
    test2();

    return 0;
}